<template>
  <div class="date-input">
    <el-date-picker
      v-model="localValue"
      :type="dateType"
      :placeholder="param.placeholder || '请选择日期'"
      :format="dateFormat"
      :value-format="valueFormat"
      :clearable="true"
      :disabled="param.disabled"
      size="medium"
      style="width: 100%"
      @change="handleChange"
    />
  </div>
</template>

<script>
export default {
  name: 'DateInput',
  props: {
    param: {
      type: Object,
      required: true
    },
    value: {
      type: [String, Date],
      default: ''
    }
  },
  data() {
    return {
      localValue: this.value
    }
  },
  computed: {
    // 日期选择器类型
    dateType() {
      const format = this.param.format || 'date'
      const typeMap = {
        date: 'date',
        datetime: 'datetime',
        time: 'time',
        month: 'month',
        year: 'year'
      }
      return typeMap[format] || 'date'
    },
    
    // 显示格式
    dateFormat() {
      const format = this.param.format || 'date'
      const formatMap = {
        date: 'yyyy-MM-dd',
        datetime: 'yyyy-MM-dd HH:mm:ss',
        time: 'HH:mm:ss',
        month: 'yyyy-MM',
        year: 'yyyy'
      }
      return this.param.displayFormat || formatMap[format] || 'yyyy-MM-dd'
    },
    
    // 值格式
    valueFormat() {
      const format = this.param.format || 'date'
      const formatMap = {
        date: 'yyyy-MM-dd',
        datetime: 'yyyy-MM-dd HH:mm:ss',
        time: 'HH:mm:ss',
        month: 'yyyy-MM',
        year: 'yyyy'
      }
      return this.param.valueFormat || formatMap[format] || 'yyyy-MM-dd'
    }
  },
  watch: {
    value(newVal) {
      this.localValue = newVal
    }
  },
  methods: {
    handleChange(value) {
      const isValid = this.validateDate(value)
      const message = isValid ? '' : '日期格式不正确'
      
      this.$emit('change', {
        value: value || '',
        isValid,
        message
      })
    },
    
    validateDate(value) {
      if (!value) {
        return !this.param.required
      }
      
      // 基本日期格式验证
      if (typeof value === 'string') {
        const dateRegexMap = {
          date: /^\d{4}-\d{2}-\d{2}$/,
          datetime: /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/,
          time: /^\d{2}:\d{2}:\d{2}$/,
          month: /^\d{4}-\d{2}$/,
          year: /^\d{4}$/
        }
        
        const regex = dateRegexMap[this.param.format] || dateRegexMap.date
        return regex.test(value)
      }
      
      return value instanceof Date
    }
  }
}
</script>

<style scoped>
.date-input {
  width: 100%;
}
</style>